import { useState } from 'react';
import Cubox from '../Cubox';

import colorScheme from '../assets/color-scheme';

import styles from './select.module.css';

const Select = ({value="", suggs, onChange, onSelectOption=e=>{}, isDisabled, color='blue', className}) => {

  const [back, fore, text] = isDisabled
  ? ['base01', 'base01', 'base06']  
  : [color, 'base00', 'base06'];

  const [isFocused, setFocused] = useState(false);

  const QBOXProps = {
		cornerRadius: 20, 
		strokeWidth: 1, 
		isOutlined: true,
		backColor: colorScheme[back],
		foreColor: colorScheme[fore],
    corners: isFocused > 0 ? ['C', 'C', 'L', 'L'] : ['C', 'C', 'C', 'C'],
	};

  const inputStyle = {
    color:colorScheme[text],
  }

  const select = (e) => {
    e.stopPropagation();
    e.preventDefault();
    onSelectOption(e);
    setFocused(false);
  }

  const blur = (e) => {
    console.log('blue')
    e.stopPropagation();
    e.preventDefault();
    setFocused(false);
  }

  const toggleFocus = () => {
    if (!isDisabled) {
      setFocused(!isFocused);
    }
  }

  const suggProps = {
    ...QBOXProps,
    corners:['L', 'L', 'C', 'C'],
    style:{
      position:'absolute',
      top:55,
      zIndex: 9999,
      background: 'white',
    },
    onBlur: blur
  }

  const inputProps = {
    spellCheck: false,
    value,
    onChange,
    className:`${styles['select']} ${className}`,
    style: inputStyle,
    disabled: isDisabled,
  }

  const suggsList = isFocused
  ? <Cubox {...suggProps}>
      <div className={styles['option-wrapper']}>
      {suggs.map((sugg, i) => <option key={i} className={styles['option']} onClick={select} value={sugg}>{sugg}</option>)}
      </div>
    </Cubox>

  : <div></div>
  
  return <div onClick={toggleFocus} style={{position: 'relative'}}>
    <Cubox {...QBOXProps} >
      <input {...inputProps} />
    </Cubox>
    {suggsList}
  </div>
}

export default Select;